package com.quanyue.haircut.order.controller;

import com.quanyue.auto.util.AssertUtils;
import com.quanyue.auto.util.ServiceResult;
import com.quanyue.auto.web.Principal;
import com.quanyue.auto.web.RequestContext;
import com.quanyue.auto.web.Scope;
import com.quanyue.auto.web.WebUtils;
import com.quanyue.haircut.domain.constant.OrderType;
import com.quanyue.haircut.domain.constant.UserRole;
import com.quanyue.haircut.domain.entity.ReserveOrder;
import com.quanyue.haircut.domain.entity.User;
import com.quanyue.haircut.order.dto.*;
import com.quanyue.haircut.order.service.OrderCountService;
import com.quanyue.haircut.order.service.PayService;
import com.quanyue.haircut.order.service.ReserveOrderService;
import com.quanyue.haircut.user.service.UserService;
import com.vhuomai.mybatis.mapper.page.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Api(tags = "预约订单")
@RestController
@RequestMapping("/api")
public class ReserveOrderController {
    @Autowired
    private ReserveOrderService reserveOrderService;
    @Autowired
    private PayService payService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderCountService orderCountService;

    @ApiOperation(value = "创建订单")
    @PostMapping(value = "/reserve/order/create", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <OrderResult> create(@RequestBody ReserveOrderCreate orderCreate,
                                              @ApiIgnore HttpServletRequest request,
                                              @ApiIgnore RequestContext context) {
        Principal principal = context.getPricipal();
        User user = context.getUser();
        Integer merchantNo = null;
        if (user == null) {
            merchantNo = userService.findById(orderCreate.getReserveOrder().getUserId()).getMerchantNo();
        } else {
            merchantNo = user.getMerchantNo();
        }
        ReserveOrder order = reserveOrderService.create(merchantNo, user, orderCreate);
        OrderResult result = new OrderResult();
        result.setReserveOrder(order);
        if (!orderCreate.getOffline() && order.getCardNo() == null) {
            if (principal.getRole().equals(UserRole.MANAGER)) {
                throw new AssertUtils.ValidateException("会员卡余额不足!");
            } else {
                result.setWxPayUnifiedOrderResult(payService.pay(OrderType.RESERVE.name(), user.getMerchantNo(), order.getPayPrice(), order.getOrderNo(), user, WebUtils.getClientIp(request)));
            }
        }
        return ServiceResult.success(result);
    }

    @ApiOperation(value = "订单列表 {用户查询：shopId传0， 管理员查询传相应的shopId}")
    @GetMapping(value = "/reserve/order/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <List <ReserveOrderDetail>> myOrder(@RequestParam Integer shopId,
                                                             @ApiIgnore Principal principal) {
        Integer userId = principal.getId();
        if (shopId != 0) userId = null;
        return ServiceResult.success(reserveOrderService.findOrderDetailList(userId, shopId));
    }

    @ApiOperation(value = "根据消费情况排除会员")
    @Scope(role = UserRole.MANAGER)
    @PostMapping(value = "/vip/user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <Page <UserByConsume>> findVipByConsume(@RequestBody UserByConsumeReq req) {
        return ServiceResult.success(reserveOrderService.findVipByConsume(req));
    }

    @ApiOperation(value = "每日营业额")
    @GetMapping(value = "/date/turnover", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <List <TurnoverResult>> dateTurnover(@RequestParam("startDate") String startDate,
                                                              @RequestParam("endDate") String endDate,
                                                              @RequestParam Integer merchantNo,
                                                              @ApiIgnore Principal principal) {
        if (merchantNo == 0) merchantNo = principal.getMerchantNo();
        return ServiceResult.success(
                orderCountService.dateTurnover(merchantNo, LocalDate.parse(startDate), LocalDate.parse(endDate)));
    }

    @ApiOperation(value = "每月营业额")
    @GetMapping(value = "/month/turnover", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <List <TurnoverResult>> monthTurnover(@RequestParam String startMonth,
                                                               @RequestParam String endMonth,
                                                               @RequestParam Integer merchantNo,
                                                               @ApiIgnore Principal principal) {
        if (merchantNo == 0) merchantNo = principal.getMerchantNo();
        return ServiceResult.success(orderCountService.monthTurnover(merchantNo, startMonth, endMonth));
    }

    @ApiOperation(value = "每日到店会员")
    @GetMapping(value = "/date/user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <List <ArriveShopCount>> dateUser(@RequestParam("startDate") String startDate,
                                                           @RequestParam("endDate") String endDate,
                                                           @RequestParam Integer merchantNo,
                                                           @ApiIgnore Principal principal) {
        if (merchantNo == 0) merchantNo = principal.getMerchantNo();
        return ServiceResult.success(orderCountService.dateArriveShop(merchantNo, LocalDate.parse(startDate), LocalDate.parse(endDate)));
    }

    @ApiOperation(value = "每月到店会员")
    @GetMapping(value = "/month/user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <List <ArriveShopCount>> monthUser(@RequestParam String startMonth,
                                                            @RequestParam String endMonth,
                                                            @RequestParam Integer merchantNo,
                                                            @ApiIgnore Principal principal) {
        if (merchantNo == 0) merchantNo = principal.getMerchantNo();
        return ServiceResult.success(orderCountService.monthArriveShop(merchantNo, startMonth, endMonth));
    }

    @ApiOperation(value = "总/当月/当日营业额统计")
    @GetMapping(value = "/total/month/date/turnover", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <Map <String, BigDecimal>> totalMonthDateTurnover(@RequestParam Integer merchantNo,
                                                                           @ApiIgnore Principal principal) {
        if (merchantNo == 0) merchantNo = principal.getMerchantNo();
        return ServiceResult.success(orderCountService.findTotalMonthDate(merchantNo));
    }

    @ApiOperation(value = "总/当月/当日营业额统计--导出Excel")
    @GetMapping(value = "/total/month/date/turnover/excel", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ServiceResult <String> monthDateTurnoverExcel(@RequestParam Integer merchantNo,
                                                         @ApiIgnore Principal principal) {
        if (merchantNo == 0) merchantNo = principal.getMerchantNo();
        return ServiceResult.success(orderCountService.createExcel(merchantNo));
    }

}
